package com.dudu.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

/**
 * https请求工具类
 * @author zx
 *
 */
public class HttpsRequest {
	private static Logger log = Logger.getLogger(HttpsRequest.class);
	public static final String charset = "UTF-8";
	
	public static final String CONTENTTYPE_APPLICATION_JSON="application/json";
	public static final String CONTENTTYPE_APPLICATION_XML ="application/xml";
	public static final String CONTENTTYPE_MULTIPART_FORM="multipart/form-data";
	public static final String TEXTPLAIN="text/plain";
	public static final String TEXTHTML="text/html";

	/** 
	* @Title: PostHttps  
	* @param @param url
	* @param @param map
	* @param @param contenttype
	* @param @return    
	* @return String    
	* @throws 
	*/ 
	public static String postHttps(String url, JSONObject map,
			String contenttype) {
		String result = "";
		HttpClient client = new HttpClient();
		Protocol myhttps = new Protocol("https",
				new MySSLProtocolSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);
		PostMethod method = new PostMethod(url);
		RequestEntity requestEntity;
		try {
			requestEntity = new StringRequestEntity(map.toString(),
					contenttype, charset);
			method.setRequestEntity(requestEntity);  
			client.executeMethod(method);
			result = method.getResponseBodyAsString();  
		} catch (Exception e) {
			e.printStackTrace();
			String err=ExceptionUtils.getStackTraceCauseMessage(e,-1);
			result= "{'success':false,'cause':'"+err+"'}";
			log.error("https请求异常",e);   
		} finally {
			// 释放连接
			method.releaseConnection();
		}
		return result;
	}
}
